package com.katze.boot.plugins.feign;

import java.net.URI;
import java.util.concurrent.ConcurrentHashMap;

public class AccessManager {

    private final ConcurrentHashMap<String, URI> uris = new ConcurrentHashMap<>();

    private final String serviceId;

    public AccessManager(String serviceId) {
        this.serviceId = serviceId;
    }

    public String getServiceId() {
        return serviceId;
    }

    /*public URI getUri() {
        if (!uris.isEmpty()) {
            //根据当前时间戳进行负载均衡(*不是很均衡)
            int millis = (int) (System.currentTimeMillis() % 1000);
            millis = millis < uris.size() ? millis : millis % uris.size();
            return uris.get(millis);
        } else {
            throw new ApplicationNotExistException("应用程序尚未配置URI或处于离线状态无法访问(" + getServiceId() +")");
        }
    }*/

    public URI getUri(String id) {
        if (!uris.isEmpty()) {
            return uris.get(id);
        } else {
            throw new ApplicationNotExistException("应用程序尚未配置URI或处于离线状态无法访问(" + getServiceId() +")");
        }
    }

    public void add(FeignUri feignUri) {
        this.uris.put(feignUri.getServiceId(), this.toURI(feignUri));
    }

    public int remove(FeignUri feignUri) {
        this.uris.remove(feignUri.getServiceId());
        return this.uris.size();
    }

    private URI toURI(FeignUri feignUri) {
        int index = feignUri.getUri().indexOf("?");
        String uri =  index != -1? feignUri.getUri().substring(0, index):feignUri.getUri();
        return URI.create(uri);
    }


}
